package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrderMapper, Orders>implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Transactional
    @Override
    public void sumbit(Orders orders, HttpSession session) {
        Long currentId = (Long) session.getAttribute("user");
        LambdaQueryWrapper<ShoppingCart>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        if(list==null||list.size()==0)
        {
            throw new CustomException("购物车为空，不能下单");
        }
        User user = userService.getById(currentId);
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if(addressBook==null)
        {
            throw new CustomException("用户地址信息有误，不能下单");
        }
        long id = IdWorker.getId();
        AtomicInteger amount=new AtomicInteger(0);
        List<OrderDetail>orderDetails=list.stream().map((item)->
        {
            OrderDetail orderDetail=new OrderDetail();
            orderDetail.setOrderId(id);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        orders.setNumber(String.valueOf(id));
        orders.setId(id);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserId(currentId);
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName()==null?"":addressBook.getProvinceName()
        +addressBook.getCityName()==null?"":addressBook.getCityName()
        +addressBook.getDistrictName()==null?"":addressBook.getDistrictName()
        +addressBook.getDetail()==null?"":addressBook.getDetail());
        orderDetailService.saveBatch(orderDetails);
        this.save(orders);
        shoppingCartService.remove(queryWrapper);
    }

    @Override
        public void again(Orders order) {
        Long orderId = order.getId();
        Orders newOrder=new Orders();
        BeanUtils.copyProperties(order,newOrder);
        long id = IdWorker.getId();
        newOrder.setNumber(String.valueOf(id));
        newOrder.setId(id);
        newOrder.setOrderTime(LocalDateTime.now());
        newOrder.setCheckoutTime(LocalDateTime.now());
        newOrder.setStatus(2);
        this.save(newOrder);
        LambdaQueryWrapper<OrderDetail>lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderDetail::getOrderId,orderId);
        List<OrderDetail> list = orderDetailService.list(lambdaQueryWrapper);
        for (OrderDetail orderDetail : list) {
           orderDetail.setOrderId(id);
           orderDetail.setId(null);
        }
        orderDetailService.saveBatch(list);
    }

}
